package com.ynet.middleground.user.model;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ynet.core.common.PagerInfo;
import com.ynet.core.exception.BusinessException;
import com.ynet.middleground.user.bean.OperationBlacListReq;
import com.ynet.middleground.user.bean.QueryBlacListInfoReq;
import com.ynet.middleground.user.common.ErrorMessageConstant;
import com.ynet.middleground.user.common.SystemConstant;
import com.ynet.middleground.user.dao.BlackWhiteListMapper;
import com.ynet.middleground.user.dao.EnterpriseBasicInfoMapper;
import com.ynet.middleground.user.dao.UserBaseInformationMapper;
import com.ynet.middleground.user.dto.BlacListInfoDto;
import com.ynet.middleground.user.entity.BlackWhiteList;
import com.ynet.middleground.user.entity.EnterpriseBasicInfo;
import com.ynet.middleground.user.entity.UserBaseInformation;

import org.apache.commons.lang.StringUtils;
import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

/**
 * @program: 2019-10-12_userCenter
 * @description: 黑白名单管理事务
 * @author: DaiGaoLe
 * @create: 2019-10-30 16:54
 **/
@Component
public class BlackListManagementModel extends ServiceImpl<BlackWhiteListMapper, BlackWhiteList> {

    /**
     * 添加黑名单操作
     */
    public static final String OPERATIONE_TYPE_0 = "0";
    /**
     * 移除黑名单操作
     */
    public static final String OPERATIONE_TYPE_1 = "1";

    @Autowired
    BlackWhiteListMapper blackWhiteListMapper;

    @Autowired
    private Mapper dozerBeanMapper;

    @Autowired
    private UserBaseInformationMapper userBaseInformationMapper;
    @Autowired
    private EnterpriseBasicInfoMapper enterpriseBasicInfoMapper;

    @Autowired
    private OrganizationManagementModel organizationManagementModel;

    /*  新增黑白名单 begin */
    @Transactional(rollbackFor = Exception.class)
    public String addBlacList(OperationBlacListReq requestObject) {
        // 声明变量 begin
        Integer operationUserId = requestObject.getOperationUserId();
        Integer userId = requestObject.getUserId();
        String channel = requestObject.getChannel();
        Integer formatId = requestObject.getFormatId();
        QueryWrapper<BlackWhiteList> queryWrapper = new QueryWrapper<>();
        // 声明变量 end


        UserBaseInformation userBaseInformation = userBaseInformationMapper.selectById(userId);
        if (userBaseInformation == null) {
            throw new BusinessException(ErrorMessageConstant.ECUC0002_MESSAGE,ErrorMessageConstant.ECUC0002_CODE);
        }

        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("channel", channel);
        queryWrapper.eq("status", SystemConstant.BLACK_LIST_STATUS_0);
        if(formatId!=null){
            if(!organizationManagementModel.checkFormatId(formatId,channel)){
                throw new BusinessException(ErrorMessageConstant.ECUC0067_MESSAGE, ErrorMessageConstant.ECUC0067_CODE);
            }
            queryWrapper.eq("format_id", formatId);
        }else{
            queryWrapper.isNull("format_id");
        }
//        BlackWhiteList temp = this.getOne(queryWrapper);



        if (blackWhiteListMapper.selectCount(queryWrapper)>0) {
            throw new BusinessException(ErrorMessageConstant.ECUC0017_MESSAGE,ErrorMessageConstant.ECUC0017_CODE);
        } else {
            BlackWhiteList temp = dozerBeanMapper.map(requestObject, BlackWhiteList.class);
            temp.setGmtCreate(LocalDateTime.now());
            temp.setCreateBy(operationUserId);
            temp.setGmtModified(LocalDateTime.now());
            temp.setModifiedBy(operationUserId);
            this.save(temp);
        }
        return SystemConstant.SYSTEM_SUCCESS;
    }
    /*  新增黑白名单 end */

    /*  移除黑白名单 begin */
    @Transactional(rollbackFor = Exception.class)
    public String removeBlacList(OperationBlacListReq requestObject) {
        // 声明变量 begin
        Integer operationUserId = requestObject.getOperationUserId();
        Integer userId = requestObject.getUserId();
        String channel = requestObject.getChannel();
        Integer formatId = requestObject.getFormatId();
        QueryWrapper<BlackWhiteList> queryWrapper = new QueryWrapper<>();
        // 声明变量 end


        UserBaseInformation userBaseInformation = userBaseInformationMapper.selectById(userId);
        if (userBaseInformation == null) {
            throw new BusinessException(ErrorMessageConstant.ECUC0002_MESSAGE,ErrorMessageConstant.ECUC0002_CODE);
        }


        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("channel", channel);
        queryWrapper.eq("status", SystemConstant.BLACK_LIST_STATUS_0);
        if(formatId!=null){
            queryWrapper.eq("format_id",formatId);
        }else{
            queryWrapper.isNull("format_id");
        }
        queryWrapper.orderByDesc("id");
        List<BlackWhiteList> blackLists = blackWhiteListMapper.selectList(queryWrapper);
//        BlackWhiteList temp = this.getOne(queryWrapper);
        if (blackLists.size()<=0) {
            throw new BusinessException(ErrorMessageConstant.ECUC0018_MESSAGE,ErrorMessageConstant.ECUC0018_CODE);
        } else {
            BlackWhiteList temp = blackLists.get(0);
            // add by gaole.dai 2019-12-31 优化使用移除愿意 begin
            temp.setBlacklistReason(requestObject.getBlacklistReason());
            // 添加渠道删除限，只有添加的渠道和删除的渠道一致的时候才能做删除操作
            if (!temp.getChannel().equals(channel)) {
                throw new BusinessException(ErrorMessageConstant.ECUC0037_MESSAGE,ErrorMessageConstant.ECUC0037_CODE);
            }
            // add by gaole.dai 2019-12-31 优化使用移除愿意 end
            temp.setStatus(SystemConstant.BLACK_LIST_STATUS_1);
            temp.setGmtModified(LocalDateTime.now());
            temp.setModifiedBy(operationUserId);
            this.updateById(temp);
        }
        return SystemConstant.SYSTEM_SUCCESS;
    }
    /*  移除黑白名单 end */


    /*  黑白名单查看 begin */
    public List<BlacListInfoDto> queryBlacList(QueryBlacListInfoReq requestObject) {
        // 声明变量 begin
        List<BlackWhiteList> records = null;
        List<BlacListInfoDto> list = new ArrayList<>();
//        Integer operationUserId = requestObject.getOperationUserId();
        Integer userId = requestObject.getUserId();
        Integer formatId = requestObject.getFormatId();
//        List<Integer> userIdList = new ArrayList<Integer>();
//        List<Integer> enterpriseIdList = new ArrayList<Integer>();
//        LambdaQueryWrapper<EnterpriseBasicInfo> queryEBI = new LambdaQueryWrapper<EnterpriseBasicInfo>();
//        queryEBI.eq(EnterpriseBasicInfo::getChannel, requestObject.getChannel());
//        queryEBI.or().like(EnterpriseBasicInfo::getAuthorizedChannels, requestObject.getChannel());
//        List<EnterpriseBasicInfo> EBInfoList = enterpriseBasicInfoMapper.selectList(queryEBI);
//        for(int i=0;i<EBInfoList.size();i++) {
//            enterpriseIdList.add(EBInfoList.get(i).getUserId());
//        }
//        if(StringUtils.isNotBlank(requestObject.getCompanyName())) {
//            queryEBI = new LambdaQueryWrapper<EnterpriseBasicInfo>();
//            queryEBI.like(EnterpriseBasicInfo::getCompanyName, requestObject.getCompanyName());
//            List<EnterpriseBasicInfo> EnterpriseBasicInfoList = enterpriseBasicInfoMapper.selectList(queryEBI);
//            for(int i=0;i<EnterpriseBasicInfoList.size();i++) {
//                userIdList.add(EnterpriseBasicInfoList.get(i).getUserId());
//            }
//        }
        QueryWrapper<BlackWhiteList> queryWrapper = new QueryWrapper<>();
        // 声明变量 end
        if(userId!=null) {
            queryWrapper.eq("user_id", userId);
        }
        if(formatId==null) {
            if (StringUtils.isNotBlank(requestObject.getCompanyName())) {
                queryWrapper.exists("select ur_black_white_list.user_id from ur_enterprise_basic_info e where ur_black_white_list.user_id = e.user_id and e.company_name like '%" + requestObject.getCompanyName() + "%' and (e.channel = '" + requestObject.getChannel() + "' or e.authorized_channels like '%" + requestObject.getChannel() + "%')");
            } else {
                queryWrapper.exists("select ur_black_white_list.user_id from ur_enterprise_basic_info e where ur_black_white_list.user_id = e.user_id and (e.channel = '" + requestObject.getChannel() + "' or e.authorized_channels like '%" + requestObject.getChannel() + "%')");
            }
        }else{
            if (StringUtils.isNotBlank(requestObject.getCompanyName())) {
                queryWrapper.exists("SELECT ur_black_white_list.user_id FROM ur_enterprise_basic_info e WHERE ur_black_white_list.user_id = e.user_id A e.company_name LIKE '%" + requestObject.getCompanyName() + "%' AND ( e.channel = '" + requestObject.getChannel() + "' OR e.authorized_channels LIKE '%"+requestObject.getChannel() + "%' ) AND (e.authorized_formats LIKE '%" + formatId + "%')");
            } else {
                queryWrapper.exists("select ur_black_white_list.user_id from ur_enterprise_basic_info e where ur_black_white_list.user_id = e.user_id and (e.channel = '" + requestObject.getChannel() + "' or e.authorized_channels like '%" + requestObject.getChannel() + "%') AND (e.authorized_formats LIKE '%" + formatId + "%')");
            }
        }
//
//        if(StringUtils.isNotBlank(requestObject.getCompanyName())) {
//            if(userIdList.size()==0){
//                userIdList.add(0);
//            }
//            //queryWrapper.in("user_id", userIdList);
//            queryWrapper.exists("select ur_black_white_list.user_id from ur_enterprise_basic_info e where ur_black_white_list.user_id = e.user_id and e.company_name like '%"+requestObject.getCompanyName()+"%')");
//        }
//        if(enterpriseIdList.size()>0) {
//            //queryWrapper.in("user_id", enterpriseIdList);
//            queryWrapper.exists("select ur_black_white_list.user_id from ur_enterprise_basic_info e where ur_black_white_list.user_id = e.user_id and (e.channel = '"+requestObject.getChannel()+"' or e.authorized_channels like '%"+requestObject.getChannel()+"%')");
//            //queryWrapper.eq("status", SystemConstant.BLACK_LIST_STATUS_0);
//        }else {
//            queryWrapper.eq("user_id", userId);
//        }
        queryWrapper.eq("status", SystemConstant.BLACK_LIST_STATUS_0);
        PagerInfo pagerInfo = requestObject.getPagerInfo();
        Page<BlackWhiteList> blackWhiteListPage = new Page<>(pagerInfo.getPageNum(), pagerInfo.getPageSize());
        IPage<BlackWhiteList> page = this.page(blackWhiteListPage, queryWrapper);
        records = page.getRecords();
        records.forEach(ojb -> {
            BlacListInfoDto blacListInfoDto = new BlacListInfoDto();
            dozerBeanMapper.map(ojb, blacListInfoDto);
            list.add(blacListInfoDto);
        });
        pagerInfo.setTotal(page.getTotal());
        return list;
    }
    /*  黑白名单查看 end */

    private List<String> stringToList(String[] value) {
        List<String> resultList = new ArrayList<>(value.length);
        for (String s : value) {
            resultList.add(s);
        }
        return resultList;
    }


}
